//
//  BmobManager.swift
//  BarCode
//
//  Created by xxcao on 2017/4/1.
//  Copyright © 2017年 MobileArtisan. All rights reserved.
//

import UIKit
import Foundation

enum NetworkResultStatus : String{
    case NRSSuccess = "NetworkResultStatusSuccess"
    case NRSFailure = "NetworkResultStatusFailure"
    case NRSOffline = "NetworkResultStatusOffline"
    
}
class BmobManager: NSObject {
    //模拟注册
    class func mockRegister () {
        
        var user = BmobUser()
        user.username = "13400074008"
        user.password = "111111"
        user.setObject("王力汉", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        user = BmobUser()
        user.username = "18662724884"
        user.password = "111111"
        user.setObject("曹兴星", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18094221200"
        user.password = "111111"
        user.setObject("邱梦芸", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18395201500"
        user.password = "111111"
        user.setObject("李子博", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13027778807"
        user.password = "111111"
        user.setObject("陈杰", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18652979542"
        user.password = "111111"
        user.setObject("赵瑞", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18516735115"
        user.password = "111111"
        user.setObject("陆意全", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        
        user = BmobUser()
        user.username = "13338675893"
        user.password = "111111"
        user.setObject("刘敏", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        
        user = BmobUser()
        user.username = "18952028959"
        user.password = "111111"
        user.setObject("彭鹏", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "15380964428"
        user.password = "111111"
        user.setObject("魏鑫", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "15195955838"
        user.password = "111111"
        user.setObject("杨坚", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13675112958"
        user.password = "111111"
        user.setObject("董宇鹏", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "15651968717"
        user.password = "111111"
        user.setObject("卞克", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "15895910907"
        user.password = "111111"
        user.setObject("朱丽楠", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13915995280"
        user.password = "111111"
        user.setObject("刘敏", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13852297081"
        user.password = "111111"
        user.setObject("梁伟", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13818057849"
        user.password = "111111"
        user.setObject("严必庆", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18512503787"
        user.password = "111111"
        user.setObject("刘鹏", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18951819782"
        user.password = "111111"
        user.setObject("董杰", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18021417499"
        user.password = "111111"
        user.setObject("唐小绪", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18061467741"
        user.password = "111111"
        user.setObject("林琳", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "15150596942"
        user.password = "111111"
        user.setObject("叶潇", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "15738776538"
        user.password = "111111"
        user.setObject("汪坤呈", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18810905361"
        user.password = "111111"
        user.setObject("刘佳佳", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "17600123655"
        user.password = "111111"
        user.setObject("柴俊", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "15951816842"
        user.password = "111111"
        user.setObject("叶果", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13675150740"
        user.password = "111111"
        user.setObject("俞弦", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18651631820"
        user.password = "111111"
        user.setObject("焦兰兰", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13810248633"
        user.password = "111111"
        user.setObject("严辉", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        
        user = BmobUser()
        user.username = "15861097927"
        user.password = "111111"
        user.setObject("齐云猛", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13813827385"
        user.password = "111111"
        user.setObject("戈程林", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18801126073"
        user.password = "111111"
        user.setObject("高弯弯", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13951612245"
        user.password = "111111"
        user.setObject("马志刚", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18019937002"
        user.password = "111111"
        user.setObject("韩帅帅", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13520246856"
        user.password = "111111"
        user.setObject("李广", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13817101266"
        user.password = "111111"
        user.setObject("贾俊超", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13813065238"
        user.password = "111111"
        user.setObject("张春平", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18512553258"
        user.password = "111111"
        user.setObject("徐华", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "18611244930"
        user.password = "111111"
        user.setObject("张兴华", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "15910881533"
        user.password = "111111"
        user.setObject("崔涛涛", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
        
        
        user = BmobUser()
        user.username = "13262965657"
        user.password = "111111"
        user.setObject("阚强", forKey: "full_name")
        user.signUpInBackground { (isSuccessful, error) in
            if(isSuccessful) {
                print("Sign up successfully")
            } else {
                print(error as Any)
            }
        }
    }
    
    //登录接口
    class func login(userName:String, psdword:String, result:@escaping (_ res:Any?, _ status:NetworkResultStatus)->(Void)) {
        BmobUser.loginInbackground(withAccount: userName, andPassword: psdword) { (user, error) in
            if(user != nil) {
                print(user!)
                let dic = ["username":user?.username,
                           "objectId":user?.objectId,
                           "fullname":user?.object(forKey: "fullname")]
                result(dic, .NRSSuccess)
            }
            else {
                print(error!)
                result(error?.localizedDescription, .NRSFailure)
            }
        }
    }
    
    //登出接口
    class func logout(result:(_ res:Any?, _ status:NetworkResultStatus)->(Void)) {
        BmobUser.logout()
    }
    
    //查询是否存在记录
    class func isExistRecord(table:String, key:String, value:String, result:@escaping (_ res:Any?, _ status:NetworkResultStatus)->(Void)){
        let bquery = BmobQuery(className: table)
        bquery?.whereKey(key, equalTo: value)
        bquery?.findObjectsInBackground({ (results, error) in
            if error != nil {
                result(error?.localizedDescription, .NRSFailure)
            } else {
                result(results, .NRSSuccess);
            }
        })
    }
    
    //绑定接口
    class func binding(userName:String, fullName:String, code:String, goodsName:String, result:@escaping (_ res:Any?, _ status:NetworkResultStatus)->(Void)) {
        let user2codeObj = BmobObject(className: "user2code")
        user2codeObj?.setObject(userName, forKey: "user_id")
        user2codeObj?.setObject(fullName, forKey: "full_name")
        user2codeObj?.setObject(code, forKey: "code")
        user2codeObj?.setObject(goodsName, forKey: "goods_name")
        user2codeObj?.saveInBackground(resultBlock: { (isSuccessful, error) in
            if(error == nil) {
                if (isSuccessful) {
                    result("绑定成功", .NRSSuccess)
                } else {
                    result("绑定失败", .NRSFailure)
                }
            } else {
                result(error?.localizedDescription, .NRSFailure)
            }
        })
    }
    
    //修改密码
    class func modifyPsdword(oldPsdword:String, newPsdword:String, result:@escaping (_ res:Any?, _ status:NetworkResultStatus)->(Void)) {
        let user = BmobUser.current()
        user?.updateCurrentUserPassword(withOldPassword: oldPsdword, newPassword: newPsdword, block: { (isSuccessful, error) in
            if isSuccessful {
                result("修改成功，请重新登录", .NRSSuccess)
                //                BmobUser.loginWithUsername(inBackground: user?.username, password: newPsdword, block: { (user1, err) in
                //                    if err != nil {
                //                        print("\(String(describing: user1))")
                //
                //                    }else{
                //                        print("login error \(String(describing: err))")
                //                    }
                //                })
            } else {
                result(error?.localizedDescription, .NRSFailure)
            }
        })
    }
    
    //获取人员接口
    class func getUsers(result: @escaping (_ res:Any?, _ status:NetworkResultStatus)->(Void)) {
        
        let bquery = BmobQuery(className: "person")
        bquery?.limit = 1000
        bquery?.findObjectsInBackground({ (results, error) in
            if(error == nil) {
                print(results as Any)
                userList.removeAll(keepingCapacity: true)
                for result in results! {
                    let tmpUser = User()
                    let dic = ["username":(result as AnyObject).object(forKey: "username"),
                               "objectId":(result as AnyObject).objectId,
                               "full_name":(result as AnyObject).object(forKey: "fullname")]
                    tmpUser.transeferDic2User(dic: dic as Any as! Dictionary<String, Any>)
                    userList.append(tmpUser)
                }
                result(userList, .NRSSuccess)
            } else {
                result(error?.localizedDescription, .NRSFailure)
            }
        })
    }
    
    //版本检测
    class func checkAppVersion(result:@escaping (_ res:Any?, _ status:NetworkResultStatus)->(Void)) {
        let query:BmobQuery = BmobQuery(className: TABLE_TT_GlobalSetting)
        query.findObjectsInBackground { (array, error) in
            if (error != nil) {
                result(error?.localizedDescription, .NRSFailure)
            } else {
                let objData = array?[0] as! BmobObject
                let serverVers = objData.object(forKey: "currentversion") as! String
                result(serverVers, .NRSSuccess)
            }
        }
    }
    
    //提交记录
    class func submitRecord(userId: String, type:NSNumber, timeStamp:String, money:NSNumber, dateStamp:String, result:@escaping (_ res:Any?, _ status:NetworkResultStatus)->(Void)) {
        let oneRecord:BmobObject = BmobObject(className: TABLE_TT_AccountRecord)
        
        oneRecord.setObject(userId, forKey: "userId")
        oneRecord.setObject(type, forKey: "type")
        
        oneRecord.setObject(timeStamp, forKey: "timeStamp")
        
        oneRecord.setObject(money, forKey: "money")
        oneRecord.setObject(dateStamp, forKey: "dateStamp")
        oneRecord.saveInBackground { [weak oneRecord] (isSuccessful, error) in
            if error != nil{
                print("error is \(error!.localizedDescription)")
            }else{
                if let record = oneRecord {
                    print("save success \(record)")
                    result(record, .NRSSuccess)
                }
            }
        }
    }
    //查询记录
    class func queryRecord(page: Int, result: @escaping (_ res:Any?, _ status:NetworkResultStatus)->(Void)) {
        //查找表
        let query = BmobQuery(className: TABLE_TT_AccountRecord)
        query?.whereKey("userId", equalTo: BmobUser.current().username)
        query?.order(byDescending: "dateStamp")
        query?.order(byDescending: "timeStamp")
        query?.limit = 10
        query?.skip = 10 * page
        query?.findObjectsInBackground { (array, error) in
            if error != nil{
                print("error is \(error!.localizedDescription)")
                result(error?.localizedDescription, .NRSFailure)
            }else {
                recordList.removeAll(keepingCapacity: true)
                print("array: /n", array as Any)
                for result in array! {
                    print(result)
                    let obj = result as! BmobObject
                    let tmpRocord = Rocord()
                    let dic:Dictionary<String, Any> = ["type":(obj as AnyObject).object(forKey: "type") as Any,
                               "timeStamp":(obj as AnyObject).object(forKey: "timeStamp") as Any,
                               "money":(obj as AnyObject).object(forKey: "money") as Any,
                               "dateStamp":(obj as AnyObject).object(forKey: "dateStamp") as Any,
                               "objectId":(obj as AnyObject).object(forKey: "objectId") as Any]
                    tmpRocord.transeferDicToUser(dic: dic)
                    recordList.append(tmpRocord)
                }
                result(recordList, .NRSSuccess)
            }
        }
    }
    
    
    //查询记录
    class func queryOneRecord(dateStamp: String, type: NSNumber, result: @escaping (_ res:Any?, _ status:NetworkResultStatus)->(Void)) {
        let query = BmobQuery(className: TABLE_TT_AccountRecord)
        query?.whereKey("userId", equalTo: BmobUser.current().username)
        let array = [["dateStamp": dateStamp],["type": type]] as [Any]
        query?.addTheConstraintByAndOperation(with: array)
        query?.limit = 1000
        query?.findObjectsInBackground { (array, error) in
            if error != nil{
                print("error is \(error!.localizedDescription)")
                result(error?.localizedDescription, .NRSFailure)
            }else {
                if array?.count != 0 {
                    result("已存在该条记录", .NRSFailure)
                } else {
                    result("不存在", .NRSSuccess)
                }
            }
        }
    }
    
    //修改数据
    class func modifyRecord(_ rocord: Rocord, _ type: NSNumber, result: @escaping (_ res:Any?, _ status:NetworkResultStatus)->(Void)) {
        let query = BmobQuery(className: TABLE_TT_AccountRecord)
        query?.whereKey("userId", equalTo: BmobUser.current().username)
        query?.getObjectInBackground(withId: rocord.objectId, block: { (obj, error) in
            if error != nil {
                print("error is \(error!.localizedDescription)")
                result(error?.localizedDescription, .NRSFailure)
            } else {
                if obj != nil {
                    let oneRecord = BmobObject.init(outDataWithClassName: obj?.className, objectId: obj?.objectId)
                    oneRecord?.setObject(BmobUser.current().username, forKey: "userId")
                    oneRecord?.setObject(type.intValue, forKey: "type")
                    
                    oneRecord?.setObject(rocord.timeStamp, forKey: "timeStamp")
                    
                    oneRecord?.setObject(NSNumber(value: NSString(string: rocord.money!).floatValue), forKey: "money")
                    oneRecord?.setObject(rocord.dateStamp, forKey: "dateStamp")
                    oneRecord?.sub_updateInBackground(resultBlock: { (isSuccess, error) in
                        if isSuccess {
                            result("提交成功", .NRSSuccess)
                        } else {
                           result(error?.localizedDescription, .NRSFailure)
                        }
                    })
                } else {
                    result(error?.localizedDescription, .NRSFailure)
                }
            }
        })
    }
    //统计查询
    class func sumQuery(result: @escaping (_ res:Any?, _ status:NetworkResultStatus)->(Void)) {
        let query:BmobQuery = BmobQuery(className: TABLE_TT_AccountRecord)
        query.whereKey("userId", equalTo: BmobUser.current().username)
        query.sumKeys(["money"])
        query.calcInBackground { (array, error) in
            if error != nil {
                print("error is \(error!.localizedDescription)")
                result(error?.localizedDescription, .NRSFailure)
            }else{
                print("array: /n", array as Any)
                if array?.count != 0 {
                    let result = array! as Array
                    let dic = (result.first as! Dictionary) as [String: AnyObject]
                    let tmpSum = dic["_sumMoney"] as! Double
                    let sum = "\(tmpSum)" 
                    sumCount = sum
                }
                result(sumCount, .NRSSuccess)
            }
        }
    }
    
}
